package owlapps2012.owlToSql.events.p4;

import java.util.Collections;
import java.util.List;

import javax.swing.JOptionPane;

import org.protege.editor.core.ui.list.MListButton;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.frame.OWLFrame;
import org.protege.editor.owl.ui.framelist.OWLFrameList;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLLiteral;


/**
* Author: Piotr Nowara<br>
* piotrnowara@gmail.com<br>
* code made available under Mozilla Public License (http://www.mozilla.org/MPL/MPL-1.1.html)<br>
* copyright 2013, Piotr Nowara<br>
*/
public class FactsDefinitioOWLFrameList<R> extends OWLFrameList<R>
{

    /**
	 * 
	 */
	private static final long serialVersionUID = -915376837784154469L;

	public FactsDefinitioOWLFrameList(OWLEditorKit editorKit, OWLFrame<R> frame) 
    {
		super(editorKit, frame);
	}
    
    protected List<MListButton> getButtons(Object value)
    {
    	if(!this.checkIfEditPossible())
    		return Collections.emptyList();
    	else
    		return super.getButtons(value);
    }
    
    protected void handleEdit()
    {
	  if (getRootObject() == null)
		    return;
      if(!this.checkAndWarnIfEditPossible())
    	  return;
      else
    	  super.handleEdit();
    }

	protected boolean checkAndWarnIfEditPossible() 
    {
		if(this.getRootObject() instanceof OWLClass)
	    	for(OWLAnnotationAssertionAxiom anAxiom : ((OWLClass)this.getRootObject()).getAnnotationAssertionAxioms(this.editorKit.getOWLModelManager().getActiveOntology()))
			{
				if(anAxiom.getProperty().isComment())
				{
					if(anAxiom.getValue() instanceof OWLLiteral && ((OWLLiteral)anAxiom.getValue()).getLiteral().startsWith("An SQL script was generated by EventsToSQLP4Transformer"))
					{
						JOptionPane.showMessageDialog(this.editorKit.getOWLWorkspace(),
				                "Unable to edit previously exported category "+((OWLClass)this.getRootObject()).getIRI().getFragment()+"\nConsider creating new version of this category.",
				                "Export selected category",
				                JOptionPane.WARNING_MESSAGE);
						return false;
					}
				}
			}
    	return true;
		
	}
	
	protected boolean checkIfEditPossible() 
	{
		if(this.getRootObject() instanceof OWLClass)
			for(OWLAnnotationAssertionAxiom anAxiom : ((OWLClass)this.getRootObject()).getAnnotationAssertionAxioms(this.editorKit.getOWLModelManager().getActiveOntology()))
			{
				if(anAxiom.getProperty().isComment())
				{
					if(anAxiom.getValue() instanceof OWLLiteral && ((OWLLiteral)anAxiom.getValue()).getLiteral().startsWith("An SQL script was generated by EventsToSQLP4Transformer"))
					{
						return false;
					}
				}
			}
		return true;
		
	}
}
